<!-- 会议信息 -->
<template>
  <div class="meeting-form">
    <a-form ref="formRef" layout="vertical" :model="formData" :rules="formRules" class="meeting-form-content" @submit="onScheduleMeetingSubmit">
      <!-- 会议类型选择 -->
      <div class="form-section">
        <h3 class="section-title">会议类型</h3>
        <a-form-item>
          <div class="meeting-type-buttons">
            <a-button
              :type="formData.meetType === '0' ? 'primary' : 'outline'"
              @click="meetingTypeFc('0')"
            >
              <template #icon>
                <icon-relation />
              </template>
              现场会议
            </a-button>
          </div>
        </a-form-item>
      </div>

      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <div class="form-row">
          <a-form-item label="会议主题" field="subject" validate-trigger="blur" class="form-item-full">
            <a-input v-model="formData.subject" placeholder="请输入会议主题" @input="onSubjectInput" />
          </a-form-item>
        </div>

        <div class="form-row">
          <a-form-item label="开始时间" field="startTime" validate-trigger="blur" class="form-item-half">
            <a-date-picker
              v-model="formData.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
              :time-picker-props="{
                format: 'HH:mm',
                hideDisabledOptions: true,
                disabledHours: () => [],
              }"
              @change="onStartTimeChange"
              @ok="onStartTimeOk"
            />
          </a-form-item>

          <a-form-item label="结束时间" field="endTime" validate-trigger="blur" class="form-item-half">
            <a-date-picker
              v-model="formData.endTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :disabled-time="disabledEndTime"
              :time-picker-props="{
                format: 'HH:mm',
                hideDisabledOptions: true,
                disabledHours: () => [],
              }"
              @change="onEndTimeChange"
              @ok="onEndTimeOk"
            />
          </a-form-item>
        </div>
      </div>

      <!-- 会议室选择 -->
      <div v-if="formData.meetType === '0' || formData.meetType === '1'" class="form-section">
        <h3 class="section-title">会议室选择 <span v-if="formData.meetType === '1'">（可选）</span></h3>
        <div class="location-selectors">
          <a-select
            v-model="selectedFactoryId"
            placeholder="请选择厂区"
            class="location-select"
            :popup-max-height="300"
            @change="onFactoryChange"
          >
            <a-option
              v-for="factory in factoryList"
              :key="factory.id"
              :value="factory.id"
              :label="factory.name"
            />
          </a-select>

          <a-select
            v-model="selectedBuildingId"
            placeholder="请选择办公楼"
            class="location-select"
            :popup-max-height="300"
            @change="onBuildingChange"
          >
            <a-option
              v-for="building in buildingList"
              :key="building.id"
              :value="building.id"
              :label="building.name"
            />
          </a-select>

          <a-select
            v-model="floor"
            placeholder="请选择楼层"
            class="location-select"
            :popup-max-height="300"
            @change="availableFloorSelectChange"
          >
            <a-option
              v-for="item of availableFloorList"
              :key="item.floor"
              :value="item.floor"
              :label="item.floor"
            />
          </a-select>
        </div>

        <div v-if="meetingRoomList.length > 0" class="meeting-room-grid">
          <div class="room-grid">
            <div v-for="item in meetingRoomList" :key="item.id" class="room-card"
                 :class="{ 'room-card-selected': formData.meetRoomId && formData.meetRoomId[0] === item.id }"
                 @click="selectMeetingRoom(item.id)">
              <div class="room-content">
                <div class="room-image">
                  <a-image :src="item.imageUrl" fit="contain" />
                </div>
                <div class="room-info">
                  <div class="room-name">{{ item.name }}</div>
                  <div class="room-details">
                    <div class="detail-item">
                      <icon-user-group />可容纳{{ item.capacity }}人
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 周期会议设置 -->
      <div class="form-section">
        <h3 class="section-title">周期设置</h3>
      <a-form-item>
          <a-checkbox v-model="isRecurringMeeting" @change="toggleRecurringMeeting">
          启用周期会议
        </a-checkbox>
      </a-form-item>

        <div v-if="isRecurringMeeting" class="cycle-settings">
          <div class="form-row">
            <a-form-item label="循环开始日期" field="cycleParams.startDate" class="form-item-half">
              <div class="readonly-date">{{ formatStartDate }}</div>
            </a-form-item>

            <a-form-item label="循环结束日期" field="cycleParams.endDate" class="form-item-half">
              <a-date-picker v-model="formData.cycleParams.endDate" format="YYYY-MM-DD" />
        </a-form-item>
          </div>

          <div class="form-row">
            <a-form-item label="循环类型" field="cycleParams.cycle" class="form-item-half">
          <a-select
                v-model="formData.cycleParams.cycle"
            placeholder="请选择循环类型"
            @change="onCycleChange"
          >
            <a-option value="Day">日</a-option>
            <a-option value="Week">周</a-option>
            <a-option value="Month">月</a-option>
          </a-select>
        </a-form-item>

            <a-form-item label="间隔周期" field="cycleParams.interval" class="form-item-half">
              <a-input-number v-model="formData.cycleParams.interval" :min="1" />
              <span class="unit-text">{{ getIntervalUnit }}</span>
        </a-form-item>
          </div>

        <template v-if="formData.cycleParams.cycle === 'Week'">
            <a-form-item label="每周选择" field="cycleParams.point">
              <a-checkbox-group v-model="formData.cycleParams.point" class="weekday-group">
              <a-checkbox value="1">星期一</a-checkbox>
              <a-checkbox value="2">星期二</a-checkbox>
              <a-checkbox value="3">星期三</a-checkbox>
              <a-checkbox value="4">星期四</a-checkbox>
              <a-checkbox value="5">星期五</a-checkbox>
              <a-checkbox value="6">星期六</a-checkbox>
              <a-checkbox value="0">星期天</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </template>

        <template v-if="formData.cycleParams.cycle === 'Month'">
            <a-form-item label="每月选择" field="cycleParams.point">
              <div class="month-days-grid">
            <a-checkbox-group v-model="formData.cycleParams.point">
                  <a-checkbox v-for="day in 31" :key="day" :value="day.toString()">
                    {{ day }}
                  </a-checkbox>
            </a-checkbox-group>
              </div>
              <span v-if="invalidDateWarning" class="warning-text">
                请注意，某些日期在二月份可能不存在。
              </span>
          </a-form-item>
        </template>
      </div>
      </div>

      <!-- 媒体类型表单项已移除，不再显示媒体类型选择 -->

      <!-- 来宾设置 -->
      <div class="form-section">
        <h3 class="section-title">来宾设置</h3>
        <div class="guest-settings">
          <a-form-item>
            <a-checkbox
              :model-value="!formData.confConfigInfo.isGuestFreePwd"
              @change="onGuestFreePwdChange"
            >
              开启来宾密码
            </a-checkbox>
          </a-form-item>

          <a-form-item v-if="!formData.confConfigInfo.isGuestFreePwd">
            <a-input
              v-model="formData.confConfigInfo.guestPwd"
              placeholder="请输入来宾密码"
            />
          </a-form-item>

          <a-form-item label="限制范围">
            <a-select
              v-model="formData.confConfigInfo.callInRestriction"
              placeholder="请选择加入限制"
            >
              <a-option :value="0">所有用户</a-option>
              <a-option :value="2">企业内用户</a-option>
              <a-option :value="3">被邀请用户</a-option>
            </a-select>
          </a-form-item>

          <a-form-item>
            <a-checkbox v-model="formData.confConfigInfo.enableWaitingRoom">
              开启等候室
            </a-checkbox>
          </a-form-item>
        </div>
      </div>

      <!-- 与会人设置 -->
      <div class="form-section">
        <h3 class="section-title">与会人设置</h3>
        <div class="attendee-settings">
          <!-- 新增：是否邀请大屏 -->
          <a-form-item label="是否邀请大屏" field="inviteScreen" class="form-item-half">
            <a-radio-group v-model="formData.inviteScreen">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="预约人">
            <div class="reservation-user-select">
              <a-button type="primary" @click="showReservationModal = true">
                选择预约人
              </a-button>
              <div v-if="selectedReservationUser" class="selected-user">
                <img
                  :src="selectedReservationUser.avatar || 'https://via.placeholder.com/30'"
                  class="user-avatar"
                />
                <span class="user-name">{{ selectedReservationUser.name }}</span>
                <span
                  class="delete-btn"
                  style="margin-left: 8px; cursor: pointer; color: #f53f3f;"
                  @click="removeReservationUser"
                >✖</span>
              </div>
            </div>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="showInviteModal = true">
              邀请与会人
            </a-button>
          </a-form-item>

          <div v-if="selectedUsers.length > 0" class="selected-users">
            <div
              v-for="(user, index) in selectedUsers"
              :key="user.userid"
              class="user-card"
              @mouseover="hoverIndex = index"
              @mouseleave="hoverIndex = -1"
            >
              <img
                :src="user.avatar || 'https://via.placeholder.com/30'"
                class="user-avatar"
              />
              <span class="user-name">{{ user.name }}</span>
              <span
                v-if="hoverIndex === index"
                class="delete-btn"
                @click="removeUser(index)"
              >✖</span>
            </div>
          </div>
          </div>
        </div>
    </a-form>

    <!-- 邀请与会人弹窗 -->
    <a-modal
      v-model:visible="showInviteModal"
      title="邀请与会人"
      :width="400"
      :height="500"
      @ok="handleInviteConfirm"
    >
      <div class="invite-modal-content">
        <a-input-search
          v-model="searchKeyword"
          placeholder="搜索部门或用户"
          class="search-input"
          :loading="searching"
          @input="handleSearch"
        />
      <a-tree
        v-model:checked-keys="checkedUserIds"
        checkable
        :data="isSearching ? searchResults : userTreeData"
        check-strictly
        @check="onCheck"
        @select="onNodeSelect"
      />
      </div>
    </a-modal>

    <!-- 预约人选择弹窗 -->
    <a-modal
      v-model:visible="showReservationModal"
      title="选择预约人"
      :width="400"
      :height="500"
      @ok="handleReservationConfirm"
    >
      <div class="invite-modal-content">
        <a-input-search
          v-model="reservationSearchKeyword"
          placeholder="搜索预约人"
          class="search-input"
          :loading="reservationSearching"
          @input="handleReservationSearch"
        />
        <a-tree
          v-model:selected-keys="selectedReservationKeys"
          :data="isReservationSearching ? reservationSearchResults : userTreeDataReservation"
          :multiple="false"
          @select="onReservationNodeSelect"
        >
          <template #icon="{ node }">
            <span v-if="node.type === 'user'" class="custom-radio">
              <input
                type="radio"
                :checked="selectedReservationKeys[0] === node.key"
                style="margin-right: 6px; vertical-align: middle;"
                @change="onReservationRadioChange(node.key)"
              />
            </span>
          </template>
        </a-tree>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { computed, ref, watch } from 'vue'
import { debounce } from 'lodash-es'
import { Message } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import type { IMeeting } from './type'
import {
  getAvailableFloor,
  getAvailablerooms,
  getBuildingList,
  getEndDatw,
  getFactoryList,
  getMeetingList,
  getUserTree,
  scheduleMeeting,
  searchTree
} from '@/apis/startApp/meeting'
import { useForm } from '@/hooks'
// 获取用户树

defineOptions({ name: 'StartApp' })
const props = defineProps({
  type: Boolean,
  meetingRoomType: Number,
  requiredSubjectMsg: { type: String, default: '请输入会议主题' },
  requiredStartTimeMsg: { type: String, default: '请选择开始时间' },
  requiredLengthMsg: { type: String, default: '请输入持续时间' },
  requiredMediaTypesMsg: { type: String, default: '请选择媒体类型' },
  requiredMeetRoomIdMsg: { type: String, default: '请选择会议室' },
  requiredGuestPwdMsg: { type: String, default: '请输入来宾密码' },
  requiredCycleStartDateMsg: { type: String, default: '请选择循环开始日期' },
  requiredCycleEndDateMsg: { type: String, default: '请选择循环结束日期' },
  requiredCycleTypeMsg: { type: String, default: '请选择循环类型' },
  requiredCyclePointMsg: { type: String, default: '请选择循环日期' },
  noMeetingInRangeMsg: { type: String, default: '您选定的时间范围内没有会议' },
  formNotInitMsg: { type: String, default: '表单实例未初始化' },
  formInvalidMsg: { type: String, default: '请检查表单填写是否正确' },
  noAttendeesMsg: { type: String, default: '请选择与会者！' },
  noUserIdMsg: { type: String, default: '用户 ID 不能为空！' },
  meetingFailedMsg: { type: String, default: '会议预约失败，请重试！' },
  searchFailedMsg: { type: String, default: '搜索失败，请稍后重试' },
  searchApiFailedMsg: { type: String, default: '搜索失败：' },
  // 新增 initialUserInfo prop
  initialUserInfo: { type: Object, default: null }
})
// 使用defineEmits注册一个自定义事件
const emit = defineEmits(['getValue', 'getMeetingType'])
// 控制邀请弹窗
const showInviteModal = ref(false)
// 控制预约会议弹窗
const showScheduleMeetingModal = ref(false)
const hoverIndex = ref(-1) // 记录鼠标悬停的索引
const treeUser = ref() // 预约人的树选择值
// 选择的厂区和办公楼
const selectedFactoryId = ref<number | null>(null)

const availableFloorList = ref([]) // 楼层列表
const selectedBuildingId = ref<number | null>(null)
// 存储树形结构数据
const userTreeData = ref<TreeNode[]>([])
const userTreeDataReservation = ref<TreeNode[]>([])
// 已选中的 `userid`（最终返回）
const selectedUsers = ref<User[]>([])

// 绑定到 `a-tree` 组件的 `checkedUserIds`
const checkedUserIds = ref<string[]>([])
const selectUserIds = ref<string[]>([])
const meetingRoomList = ref<
  {
    id: number
    name: string
    floor: string
    capacity: number
    imageUrl: string
    roomStatus: string
  }[]
>([])

const route = useRoute()
let userId
  = route.params.userId?.toString() || route.query.userId?.toString() || null
const meetingLoading = ref(false)
const meetingList = ref<IMeeting[]>([])
const noDataState = ref(false)
// 厂区数据
const factoryList = ref<{ id: number, name: string }[]>([])
const buildingList = ref<{ id: number, name: string }[]>([])
// 是否启用周期会议
const isRecurringMeeting = ref(false)
// 周期会议参数状态
// const cycleParams = ref({
//   startDate: dayjs().format('YYYY-MM-DD'),
//   endDate: '',
//   cycle: '',
//   interval: 1,
//   point: [] // 周期点
// })

// 计算循环开始日期（只读）
const formatStartDate = computed(() => {
  // 获取会议开始时间的日期部分
  return dayjs(formData.value.startTime).format('YYYY-MM-DD')
})

// 计算间隔单位
const getIntervalUnit = computed(() => {
  switch (formData.value.cycleParams.cycle) {
    case 'Day':
      return '天'
    case 'Week':
      return '周'
    case 'Month':
      return '月'
    default:
      return '天'
  }
})

// 用于标识是否存在无效日期的警告
const invalidDateWarning = ref(false)
// 选中的日期状态
const selectedDate = ref(dayjs().format('YYYY-MM-DD'))
/**
 * 会议类型切换的值
 */
const meetingTypeFc = (type: string) => {
  formData.value.meetType = type

  // 当切换会议类型时，主动清空会议室选择
  formData.value.meetRoomId = []

  // 当选择现场会议(0)时，自动设置mediaTypes为Video
  if (type === '0') {
    formData.value.mediaTypes = 'Video'
  }

  emit('getMeetingType', type)
  emit('get-value', formData.value)
}
/**
 * 选择预约人
 */
const treeUserChange = () => {
  userId = treeUser.value
  console.log(userId)
}
watch(selectedDate, (newDate) => {
  // fetchRoomStatus(newDate);
})
// 在办公楼变化时调用此方法
watch(selectedBuildingId, (newBuildingId) => {
  if (newBuildingId) {
    // fetchRoomStatus(newBuildingId);
  }
})
/**
 * 删除与会人事件
 */
const removeUser = (index: number) => {
  const removedUserId = selectedUsers.value[index].userid

  // 1️⃣ 从 `selectedUsers` 里删除该用户
  selectedUsers.value.splice(index, 1)

  // 2️⃣ 同步更新 `a-tree` 组件的 `checkedUserIds`
  checkedUserIds.value = checkedUserIds.value.filter(
    (id) => id !== removedUserId
  )

  selectUserIds.value = selectUserIds.value.filter(
    (id) => id !== removedUserId
  )

  // 新增：如果删除的与会人正好是预约人，不要清空treeUser
  // 只在removeReservationUser时才清空treeUser

  // 新增：每次与会人变化都emit最新数据
  emit('get-value', formData.value)
}
// 处理周期类型的变化
const onCycleChange = (value) => {
  formData.value.cycleParams.cycle = value

  if (value === 'Day') {
    formData.value.cycleParams.point = [] // 清空周期点
  } else if (value === 'Week') {
    formData.value.cycleParams.point = [] // 重新设置为数组，以便用户选择周几
  } else if (value === 'Month') {
    formData.value.cycleParams.point = null // 清掉 `point`
  }
}
const floor = ref() // 楼层
// 会议表单数据
const formData = ref({
  subject: '',
  startTime: dayjs().add(5 - (dayjs().minute() % 5), 'minute').format('YYYY-MM-DD HH:mm:ss'),
  endTime: dayjs().add(5 - (dayjs().minute() % 5), 'minute').add(30, 'minute').format('YYYY-MM-DD HH:mm:ss'),
  length: 30, // 默认30分钟，符合最短15分钟的要求
  mediaTypes: 'HDVideo',
  meetRoomId: '',
  meetType: '0',
  inviteScreen: 0, // 新增字段，默认不邀请
  confConfigInfo: {
    isGuestFreePwd: true, // 默认为true（免密），复选框不选中
    callInRestriction: 0,
    guestPwd: '',
    enableWaitingRoom: false
  },
  cycleParams: {
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: '',
    cycle: '',
    interval: 1,
    point: [] // 周期点
  }
})
/**
 * 根据周期会议的开始时间和结束时间判断有无会议
 * @param value 结束时间
 */
const endDateFc = async () => {
  const res = await getEndDatw(formData.value.cycleParams)
  if (res.success === false) {
    Message.error(props.noMeetingInRangeMsg)
  }
}
/**
 * 来宾密码变化事件
 */
const onGuestFreePwdChange = (checked) => {
  formData.value.confConfigInfo.isGuestFreePwd = !checked // 取反，因为我们的复选框值与isGuestFreePwd相反
  if (checked) { // 如果选中复选框，表示需要密码
    formData.value.confConfigInfo.guestPwd = Math.floor(100000 + Math.random() * 900000).toString()
  } else { // 如果取消选中复选框，表示免密
    formData.value.confConfigInfo.guestPwd = ''
  }
}
const onStartTimeOk = (timeString) => {
  // 确保时间选择器确认时也使用相同的时间格式
  formData.value.startTime = dayjs(timeString)
    .set('second', 0)
    .format('YYYY-MM-DD HH:mm:ss')
  // 计算持续时间
  calculateDuration()
}

const onEndTimeChange = (timeString) => {
  // 将时间字符串转换为dayjs对象
  const dateTime = dayjs(timeString)
  // 更新结束时间，将秒数设置为00
  formData.value.endTime = dateTime
    .set('second', 0)
    .format('YYYY-MM-DD HH:mm:ss')
  // 计算持续时间
  calculateDuration()
  // 新增：每次时间变更后都emit最新数据
  emit('get-value', formData.value)
}

const onEndTimeOk = (timeString) => {
  // 确保时间选择器确认时也使用相同的时间格式
  formData.value.endTime = dayjs(timeString)
    .set('second', 0)
    .format('YYYY-MM-DD HH:mm:ss')
  // 计算持续时间
  calculateDuration()
}

// 计算持续时间并验证时长限制
const calculateDuration = () => {
  if (formData.value.startTime && formData.value.endTime) {
    const start = dayjs(formData.value.startTime)
    const end = dayjs(formData.value.endTime)
    const duration = end.diff(start, 'minute')

    // 检查时长是否在有效范围内
    if (duration < 15) {
      // 如果小于15分钟，自动调整结束时间
      formData.value.endTime = start.add(15, 'minute').format('YYYY-MM-DD HH:mm:ss')
      formData.value.length = 15
      Message.warning('会议时长最短为15分钟，已自动调整')
    } else if (duration > 1440) {
      // 如果大于1440分钟(24小时)，自动调整结束时间
      formData.value.endTime = start.add(1440, 'minute').format('YYYY-MM-DD HH:mm:ss')
      formData.value.length = 1440
      Message.warning('会议时长最长为24小时(1440分钟)，已自动调整')
    } else if (duration > 0) {
      formData.value.length = duration
    }
  }
}

// 结束时间禁用设置
function disabledEndTime(date) {
  const now = dayjs()
  if (!date) return {}

  // 只对今天做限制
  if (dayjs(date).isSame(now, 'day')) {
    const currentHour = now.hour()
    const currentMinute = now.minute()
    return {
      disabledHours: () => Array.from({ length: 24 }, (_, i) => i).filter((i) => i < currentHour),
      disabledMinutes: (selectedHour) => {
        if (selectedHour === currentHour) {
          return Array.from({ length: 60 }, (_, i) => i).filter((i) => i < currentMinute)
        }
        return []
      }
    }
  }
  return {}
}
// 切换周期会议状态
const toggleRecurringMeeting = () => {
  if (isRecurringMeeting.value) {
    // 如果选中，设置循环开始日期为会议开始时间的日期部分
    formData.value.cycleParams.startDate = dayjs(formData.value.startTime).format('YYYY-MM-DD')
  } else {
    // 如果取消勾选，重置周期参数
    formData.value.cycleParams = {
      startDate: dayjs().format('YYYY-MM-DD'),
      endDate: '',
      cycle: '',
      interval: 1,
      point: []
    }
  }
}
watch(
  selectedUsers,
  (newUsers) => {
    checkedUserIds.value = newUsers.map((user) => user.userid)
  },
  { deep: true }
)
// 自定义时间禁用设置，使分钟只能选择每15分钟的时间
function disabledTime(date) {
  const now = dayjs()
  if (!date) return {}
  // 只对今天做限制
  if (dayjs(date).isSame(now, 'day')) {
    const currentHour = now.hour()
    const currentMinute = now.minute()
    return {
      disabledHours: () => Array.from({ length: 24 }, (_, i) => i).filter((i) => i < currentHour),
      disabledMinutes: (selectedHour) => {
        if (selectedHour === currentHour) {
          return Array.from({ length: 60 }, (_, i) => i).filter((i) => i < currentMinute)
        }
        return []
      }
    }
  }
  return {}
}
function disabledDate(current) {
  // 禁止选择今天之前的日期
  return current && current < dayjs().startOf('day')
}
// 获取厂区数据
const fetchFactories = async () => {
  try {
    factoryList.value = await getFactoryList()
    // 新增：如果有id为254的厂区，自动选中
    const defaultFactory = factoryList.value.find((f) => f.id === 254)
    if (defaultFactory) {
      selectedFactoryId.value = 254
      onFactoryChange(254)
    }
  } catch (error) {
    console.error('获取厂区失败:', error)
  }
}

// 当厂区变化时，获取办公楼数据和会议室列表
const onFactoryChange = async (value) => {
  selectedBuildingId.value = null
  floor.value = null
  buildingList.value = await getBuildingList(value)
  // 获取会议室列表
  const res = await getAvailablerooms({
    factoryId: value,
    startTime: formData.value.startTime,
    continuedTime: formData.value.length
  })
  meetingRoomList.value = res.data
}
/**
 * 会议室选择事件
 * @param value 楼层id值
 */
const meetingRoomrediogroup = (value) => {
  formData.value.meetRoomId = [value] // 将单选的值转换为数组形式
}
/**
 * 根据办公楼id获取楼层列表
 * @param value 办公楼id
 */
const availableFloorChange = async (value?) => {
  const res = await getAvailableFloor(value)
  availableFloorList.value = res.data
}
/**
 * 选择办公楼事件
 */
const onBuildingChange = async (value) => {
  floor.value = null
  availableFloorChange(value)
  // 获取会议室列表
  const res = await getAvailablerooms({
    factoryId: selectedFactoryId.value,
    buildingId: value,
    startTime: formData.value.startTime,
    continuedTime: formData.value.length
  })
  meetingRoomList.value = res.data
}
/**
 * 楼层选择事件
 */
const availableFloorSelectChange = async (value?) => {
  meetingRoomList.value = []
  // 判断是选择器选择触发，还是监听器触发
  if (value) {
    floor.value = value
  }

  // 获取会议室列表
  const res = await getAvailablerooms({
    factoryId: selectedFactoryId.value,
    buildingId: selectedBuildingId.value,
    floor: floor.value,
    startTime: formData.value.startTime,
    continuedTime: formData.value.length
  })
  meetingRoomList.value = res.data
}

// 在表单中的开始时间和结束时间变化时，执行相关逻辑
watch(
  () => [formData.value.startTime, formData.value.endTime],
  ([newStartTime, newEndTime], [oldStartTime, oldEndTime]) => {
    if (
      formData.value.meetType === '0'
      && (newStartTime !== oldStartTime || newEndTime !== oldEndTime)
    ) {
      availableFloorSelectChange()
    }

    // 更新循环会议的开始日期
    if (isRecurringMeeting.value) {
      formData.value.cycleParams.startDate = dayjs(formData.value.startTime).format('YYYY-MM-DD')
    }
  }
)

watch(
  () => formData.value.meetType,
  (newValue) => {
    // 会议类型变更时自动设置媒体类型
    if (newValue === '0') {
      formData.value.mediaTypes = 'Video'
    } else if (newValue === '1') {
      formData.value.mediaTypes = ''
    }
    console.log('会议类型变更:', newValue)
    console.log('会议类型变更:', formData.value.meetType)
  }
)
// 关闭预约会议弹窗
// 转换数据格式（确保 `userid` 绑定正确）
const transformTreeData = (data: any[]) => {
  return data.map((node) => ({
    title: node.name,
    key: node.type === 'user' ? node.userid : node.id?.toString(),
    value: node.type === 'user' ? node.userid : node.id?.toString(),
    selectable: true,
    disabled: node.type === 'department',
    children:
      node.children && node.children.length > 0
        ? transformTreeData(node.children)
        : [],
    avatar: node.avatar || null,
    type: node.type
  }))
}
// 递归查找用户节点（根据 userid）
const findUserById = (tree, userid) => {
  for (const node of tree) {
    if (node.value === userid) return node
    if (node.children) {
      const found = findUserById(node.children, userid)
      if (found) return found
    }
  }
  return null
}

// 搜索功能
const searching = ref(false)
const reservationSearching = ref(false)

// 使用 lodash 的 debounce 优化搜索
const handleSearch = debounce(async (value: string) => {
  console.error('搜索输入:', value) // 记录搜索输入
  console.error('当前选中用户:', selectedUsers.value) // 记录当前选中用户

  if (!value) {
    console.error('清除搜索') // 记录清除搜索动作
    // 清空搜索时，恢复到完整树视图，但保持选中状态
    isSearching.value = false
    searching.value = false
    searchResults.value = [] // 清空搜索结果

    // 确保树视图显示正确的选中状态
    // 将已选择的用户ID同步到checkedUserIds
    checkedUserIds.value = selectedUsers.value.map((user) => user.userid)
    return
  }

  searching.value = true
  try {
    console.error('发起搜索请求:', value) // 记录发起搜索
    const res = await searchTree(value)

    if (res.code === '0' && res.success) {
      // 获取已选择的用户ID列表
      const selectedUserIds = selectedUsers.value.map((user) => user.userid)
      console.error('搜索成功,已选用户IDs:', selectedUserIds) // 记录搜索成功和已选用户

      // 转换搜索结果，确保正确的选中状态
      const results = transformSearchResults(res.data)

      // 设置搜索结果
      searchResults.value = results
      isSearching.value = true

      // 确保checkedUserIds与selectedUsers同步
      checkedUserIds.value = selectedUserIds

      console.error('搜索结果处理完成,结果数量:', results.length) // 记录处理完成
    } else {
      console.error('搜索失败:', res.msg) // 记录搜索失败
      Message.error(`${props.searchApiFailedMsg}${res.msg}`)
    }
  } catch (error) {
    console.error('搜索出错:', error) // 记录搜索错误
    Message.error(props.searchFailedMsg)
  } finally {
    searching.value = false
  }
}, 300)

// 修改onCheck函数
const onCheck = (checkedKeys, event) => {
  // 在check-strictly模式下，event包含node和checked信息
  const { checked, node } = event

  // 只处理用户节点
  if (node.type !== 'user') return

  if (checked) {
    // 如果是选中操作，添加到checkedUserIds
    if (!checkedUserIds.value.includes(node.key)) {
      checkedUserIds.value.push(node.key)
    }

    // 添加用户到selectedUsers
    const userExists = selectedUsers.value.some((user) => user.userid === node.key)
    if (!userExists) {
      selectedUsers.value.push({
        userid: node.key,
        name: node.title,
        avatar: node.avatar || ''
      })
    }
  } else {
    // 如果是取消选中操作，从checkedUserIds中移除
    checkedUserIds.value = checkedUserIds.value.filter((id) => id !== node.key)

    // 同时从selectedUsers中移除
    selectedUsers.value = selectedUsers.value.filter((user) => user.userid !== node.key)
  }
}

// 修改handleInviteConfirm函数
const handleInviteConfirm = () => {
  console.error('确认选择,当前选中用户:', selectedUsers.value.map((u) => u.name).join(','))
  showInviteModal.value = false
}

// 将搜索结果转换为树形结构
const transformSearchResults = (data: any[]) => {
  // 获取已选择的用户ID列表
  const selectedUserIds = selectedUsers.value.map((user) => user.userid)

  // 转换数据结构
  const result = data.map((item) => {
    // 确保保留所有原始属性
    const isUser = item.type === 'user' || item.userid
    const userId = isUser ? (item.userid || item.key || item.id) : null

    // 构建基本树节点
    const treeNode = {
      key: userId || item.id?.toString() || item.key,
      title: item.name || item.title,
      type: item.type || (isUser ? 'user' : 'department'),
      userid: userId,
      avatar: item.avatar,
      isLeaf: !item.children || item.children.length === 0,
      selectable: true, // 允许选择
      checked: isUser && selectedUserIds.includes(userId)
    }

    return treeNode
  })

  return result
}

// 获取用户树数据
const fetchUserTree = async () => {
  try {
    const rawData = await getUserTree()
    userTreeData.value = transformTreeData(rawData)
    userTreeDataReservation.value = transformTreeData(rawData)
  } catch (error) {
    console.error('获取用户树失败:', error)
  }
}
const { form } = useForm({
  keyword: ''
})
/**
 * 获取会议列表
 */
const fatchMeetingList = debounce(() => {
  const params = { userId, ...form }
  meetingLoading.value = true
  getMeetingList(params)
    .then((res) => {
      meetingList.value = res.data
      noDataState.value = res.data.length == 0
      meetingLoading.value = false
    })
    .catch((_err) => {
      noDataState.value = true
      meetingLoading.value = false
    })
}, 500)

watch(form, (_newValue, _oldValue) => {
  fatchMeetingList()
})
document.addEventListener(
  'touchmove',
  (e) => {
    e.passive = true
  },
  { capture: false, passive: true }
)
watch(selectedDate, (newDate) => {
  // fetchRoomStatus(newDate);
})
const onStartTimeChange = (timeString) => {
  // 将时间字符串转换为dayjs对象
  const dateTime = dayjs(timeString)
  // 更新开始时间，将秒数设置为00
  formData.value.startTime = dateTime
    .set('second', 0)
    .format('YYYY-MM-DD HH:mm:ss')
  // 计算持续时间
  calculateDuration()
  // 新增：每次时间变更后都emit最新数据
  emit('get-value', formData.value)
}
// 重置表单函数
const resetForm = () => {
  formData.value = {
    subject: '',
    startTime: dayjs().add(5 - (dayjs().minute() % 5), 'minute').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().add(5 - (dayjs().minute() % 5), 'minute').add(30, 'minute').format('YYYY-MM-DD HH:mm:ss'),
    length: 30, // 默认30分钟，符合最短15分钟的要求
    mediaTypes: 'HDVideo',
    meetRoomId: '',
    meetType: '0',
    inviteScreen: 0, // 新增字段，默认不邀请
    confConfigInfo: {
      isGuestFreePwd: true, // 默认为true（免密），复选框不选中
      callInRestriction: 0,
      guestPwd: '',
      enableWaitingRoom: false
    },
    cycleParams: {
      startDate: dayjs().format('YYYY-MM-DD'),
      endDate: '',
      cycle: '',
      interval: 1,
      point: []
    }
  }
  selectedFactoryId.value = null
  selectedBuildingId.value = null
  selectedUsers.value = []
  checkedUserIds.value = []
  isRecurringMeeting.value = false // 重置周期会议状态
  treeUser.value = null
  // 新增：重置预约人弹窗相关状态
  selectedReservationKeys.value = []
  selectedReservationUser.value = null
}
// 提交预约会议
const onScheduleMeetingSubmit = async () => {
  try {
    // 先进行表单验证
    if (!formRef.value) {
      Message.error(props.formNotInitMsg)
      return false
    }

    const validateResult = await formRef.value.validate()
    if (validateResult) {
      Message.error(props.formInvalidMsg)
      return false
    }

    if (!selectedUsers.value.length) {
      Message.error(props.noAttendeesMsg)
      return false
    }

    if (!userId) {
      Message.error(props.noUserIdMsg)
      return false
    }

    const requestData = {
      userId,
      subject: formData.value.subject,
      startTime: formData.value.startTime,
      length: formData.value.length,
      mediaTypes: formData.value.mediaTypes || 'HDVideo',
      meetRoomId: formData.value.meetRoomId,
      meetType: formData.value.meetType,
      inviteScreen: formData.value.inviteScreen, // 新增邀请大屏参数
      confConfigInfo: {
        isGuestFreePwd: formData.value.confConfigInfo?.isGuestFreePwd || false,
        callInRestriction: formData.value.confConfigInfo?.callInRestriction || 0,
        guestPwd: formData.value.confConfigInfo?.guestPwd || '',
        enableWaitingRoom: formData.value.confConfigInfo?.enableWaitingRoom || false
      },
      cycleParams: isRecurringMeeting.value
        ? {
            startDate: formData.value.cycleParams.startDate,
            endDate: formData.value.cycleParams.endDate,
            cycle: formData.value.cycleParams.cycle,
            interval: formData.value.cycleParams.interval,
            point: formData.value.cycleParams.point
          }
        : undefined,
      attendees: selectedUsers.value.map((user) => ({
        accountId: user.userid,
        appId: '9dbd6b334e744eada42b45b3bf6b8402'
      }))
    }

    const res = await scheduleMeeting(requestData)

    if (res.success) {
      Message.success('会议预约成功！')
      resetForm()
      fetchUserTree()
      showScheduleMeetingModal.value = false
      await fatchMeetingList()
      return true
    } else {
      Message.error(res.msg || props.meetingFailedMsg)
      return false
    }
  } catch (error: any) {
    console.error('提交会议失败:', error)
    if (error.name === 'ValidateError') {
      Message.error(props.formInvalidMsg)
      return false
    }
    Message.error(error.message || props.meetingFailedMsg)
    return false
  } finally {
    meetingRoomList.value = []
  }
}

watch(
  () => props.type, // 监听的属性
  (newVal, oldVal) => {
    // 变化时的回调函数
    console.log(`旧 ${oldVal} 新 ${newVal}`)
    formData.value.selectedUsers = selectedUsers.value
    formData.value.treeUser = treeUser.value
    // 保证全文件只用formData.value.cycleParams
    formData.value.cycleParams = formData.value.cycleParams
    emit('getValue', formData.value)
  }
)
onMounted(() => {
  console.log(props.meetingRoomType)

  fetchUserTree()
  // 组件初始化时获取厂区数据
  fetchFactories()
  selectedDate.value = dayjs().format('YYYY-MM-DD') // 初始化当天的日期
  if (selectedBuildingId.value) {
    // fetchRoomStatus(selectedDate.value);
  }
  const now = dayjs()
  const minutes = now.minute()
  const remainder = minutes % 5
  const nextMinutes = remainder === 0 ? minutes : minutes + (5 - remainder)

  formData.value.startTime = now.set('minute', nextMinutes).set('second', 0).format('YYYY-MM-DD HH:mm:ss')
  formData.value.endTime = now.set('minute', nextMinutes).set('second', 0).add(30, 'minute').format('YYYY-MM-DD HH:mm:ss')
  formData.value.length = 30 // 默认30分钟，符合最短15分钟的要求

  // 新增：初始化时自动emit一次get-value，确保父组件拿到初始表单数据
  emit('get-value', formData.value)
  // onMounted 时，如果 meetingRoomType=1，强制设置 formData.meetType = '0'
  if (props.meetingRoomType === 1) {
    formData.value.meetType = '0'
  }
})

const searchKeyword = ref('')
const isSearching = ref(false)
const searchResults = ref<TreeNode[]>([])

const reservationSearchKeyword = ref('')
const isReservationSearching = ref(false)
const reservationSearchResults = ref<TreeNode[]>([])

// 预约人搜索
const handleReservationSearch = debounce(async (value: string) => {
  if (!value) {
    isReservationSearching.value = false
    reservationSearchResults.value = []
    reservationSearching.value = false
    return
  }

  reservationSearching.value = true
  try {
    const res = await searchTree(value)
    if (res.code === '0' && res.success) {
      reservationSearchResults.value = transformSearchResults(res.data)
      isReservationSearching.value = true
    } else {
      Message.error(`${props.searchApiFailedMsg}${res.msg}`)
    }
  } catch (error) {
    Message.error(props.searchFailedMsg)
  } finally {
    reservationSearching.value = false
  }
}, 300)

// 处理预约人选择
const selectedReservationKeys = ref<string[]>([])

// 监听选中的变化
watch(selectedReservationKeys, (newKeys) => {
  if (newKeys && newKeys.length > 0) {
    treeUser.value = newKeys[0]
    userId = newKeys[0]
    // 从搜索结果或树形数据中找到用户信息
    const userInfo = isReservationSearching.value
      ? reservationSearchResults.value.find((item) => item.key === newKeys[0])
      : findUserById(userTreeDataReservation.value, newKeys[0])

    if (userInfo) {
      console.log('Selected user:', userInfo)
    }
  }
})

const showReservationModal = ref(false)
const selectedReservationUser = ref<User | null>(null)

// 处理预约人确认选择
const handleReservationConfirm = () => {
  if (selectedReservationKeys.value && selectedReservationKeys.value.length > 0) {
    const selectedKey = selectedReservationKeys.value[0]
    // 从搜索结果或树形数据中找到用户信息
    const userInfo = isReservationSearching.value
      ? reservationSearchResults.value.find((item) => item.key === selectedKey)
      : findUserById(userTreeDataReservation.value, selectedKey)

    if (userInfo) {
      selectedReservationUser.value = {
        userid: userInfo.userid || userInfo.value,
        name: userInfo.title,
        avatar: userInfo.avatar || ''
      }
      treeUser.value = selectedKey
      userId = selectedKey

      // 修正：始终确保预约人在selectedUsers中
      const reservationUser = {
        userid: userInfo.userid || userInfo.value,
        name: userInfo.title,
        avatar: userInfo.avatar || ''
      }
      // 先移除同userid的用户，避免重复
      selectedUsers.value = selectedUsers.value.filter((user) => user.userid !== reservationUser.userid)
      selectedUsers.value.push(reservationUser)
      // 更新选中状态
      checkedUserIds.value = Array.from(new Set([...checkedUserIds.value, reservationUser.userid]))
    }
  }
  // 修正：emit前同步treeUser
  formData.value.treeUser = treeUser.value
  console.log('handleReservationConfirm emit selectedUsers:', selectedUsers.value)
  emit('get-value', formData.value)
  showReservationModal.value = false
}

// 在script setup开始处添加类型定义
interface User {
  userid: string
  name: string
  avatar: string
}

interface TreeNode {
  key: string
  title: string
  type: string
  userid: string
  avatar: string
  isLeaf: boolean
  selectable: boolean
  checked: boolean
  children?: TreeNode[]
}

// 添加表单验证规则
const formRules = {
  'subject': [{ required: true, message: props.requiredSubjectMsg }],
  'startTime': [{ required: true, message: props.requiredStartTimeMsg }],
  'endTime': [{ required: true, message: '请选择结束时间' }],
  'length': [
    { required: true, message: props.requiredLengthMsg },
    {
      validator: (value, callback) => {
        if (value < 15) {
          callback('会议时长不能少于15分钟')
        } else if (value > 1440) {
          callback('会议时长不能超过24小时(1440分钟)')
        } else {
          callback()
        }
      }
    }
  ],
  'mediaTypes': [{ required: true, message: props.requiredMediaTypesMsg, validator: (value, callback) => {
    if (formData.value.meetType === '1' && !value) {
      callback(props.requiredMediaTypesMsg)
    } else {
      callback()
    }
  } }],
  'meetRoomId': [{ required: true, message: props.requiredMeetRoomIdMsg, validator: (value, callback) => {
    if (formData.value.meetType === '0' && !value) {
      callback(props.requiredMeetRoomIdMsg)
    } else {
      callback()
    }
  } }],
  'confConfigInfo.guestPwd': [{ required: true, message: props.requiredGuestPwdMsg, validator: (value, callback) => {
    if (!formData.value.confConfigInfo.isGuestFreePwd && !value) {
      callback(props.requiredGuestPwdMsg)
    } else {
      callback()
    }
  } }],
  'cycleParams.startDate': [{ required: true, message: props.requiredCycleStartDateMsg, validator: (value, callback) => {
    if (isRecurringMeeting.value && !value) {
      callback(props.requiredCycleStartDateMsg)
    } else {
      callback()
    }
  } }],
  'cycleParams.endDate': [{ required: true, message: props.requiredCycleEndDateMsg, validator: (value, callback) => {
    if (isRecurringMeeting.value && !value) {
      callback(props.requiredCycleEndDateMsg)
    } else {
      callback()
    }
  } }],
  'cycleParams.cycle': [{ required: true, message: props.requiredCycleTypeMsg, validator: (value, callback) => {
    if (isRecurringMeeting.value && !value) {
      callback(props.requiredCycleTypeMsg)
    } else {
      callback()
    }
  } }],
  'cycleParams.point': [{ required: true, message: props.requiredCyclePointMsg, validator: (value, callback) => {
    // 未启用周期会议时不验证
    if (!isRecurringMeeting.value) {
      callback()
      return
    }

    // 未选择循环类型时不验证
    if (!formData.value.cycleParams.cycle) {
      callback()
      return
    }

    // 根据不同循环类型验证
    if (formData.value.cycleParams.cycle === 'Week') {
      // 周模式必须选择每周几
      if (!value || !Array.isArray(value) || value.length === 0) {
        callback('请选择每周的会议日期')
      } else {
        callback()
      }
    } else if (formData.value.cycleParams.cycle === 'Month') {
      // 月模式必须选择每月哪几天
      if (!value || !Array.isArray(value) || value.length === 0) {
        callback('请选择每月的会议日期')
      } else {
        callback()
      }
    } else {
      // 日模式不需要选择具体时间点
      callback()
    }
  } }],
  'inviteScreen': [{ required: true, message: '请选择是否邀请大屏' }]
}

// 添加表单引用
const formRef = ref()

// 暴露验证方法给父组件
const validateForm = async () => {
  try {
    if (!formRef.value) {
      Message.error(props.formNotInitMsg)
      return false
    }
    await formRef.value.validate()
    return true
  } catch (error) {
    console.error('表单验证失败:', error)
    return false
  }
}

// 添加表单验证状态
const isFormValid = ref(false)

// 监听表单验证状态
watch(() => formRef.value, async (newVal) => {
  if (newVal) {
    try {
      await newVal.validate()
      isFormValid.value = true
    } catch (error) {
      isFormValid.value = false
    }
  }
}, { immediate: true })

// 暴露给父组件的方法
defineExpose({
  validateForm,
  onScheduleMeetingSubmit,
  formRef,
  isFormValid,
  resetForm
})

// 添加对showInviteModal的监听
watch(showInviteModal, (newValue) => {
  if (newValue) {
    console.error('打开邀请弹窗,当前选中用户:', selectedUsers.value.map((u) => u.name).join(','))
    // 当弹窗打开时，确保checkedUserIds反映当前选中的所有用户
    checkedUserIds.value = selectedUsers.value.map((user) => user.userid)

    // 重置搜索状态
    searchKeyword.value = ''
    isSearching.value = false
    // 不清空searchResults，这样能保持上次的搜索结果
  } else {
    console.error('关闭邀请弹窗后,最终选中用户:', selectedUsers.value.map((u) => u.name).join(','))
    // 弹窗关闭时再次确认checkedUserIds与selectedUsers同步
    checkedUserIds.value = selectedUsers.value.map((user) => user.userid)
  }
})

// 处理表单数据提交
const handleSubmit = () => {
  const submitData = {
    ...formData.value,
    confConfigInfo: {
      ...formData.value.confConfigInfo,
      // 修正isGuestFreePwd的逻辑：true表示免密，false表示需要密码
      isGuestFreePwd: !formData.value.confConfigInfo.isGuestFreePwd,
      // 如果isGuestFreePwd为true(免密)，则不需要密码；如果为false(需要密码)，则必须有密码
      guestPwd: !formData.value.confConfigInfo.isGuestFreePwd ? (formData.value.confConfigInfo.guestPwd || '') : ''
    }
  }

  emit('get-value', submitData)
}

// 获取下一个整5或整10分钟的时间
const getNextRoundedTime = () => {
  const now = dayjs()
  const minutes = now.minute()
  const remainder = minutes % 10
  let nextMinutes = minutes

  if (remainder < 5) {
    nextMinutes = minutes + (5 - remainder)
  } else if (remainder < 10) {
    nextMinutes = minutes + (10 - remainder)
  } else {
    nextMinutes = minutes + 5
  }

  return now.set('minute', nextMinutes).set('second', 0)
}

// 修改onNodeSelect函数
const onNodeSelect = (selectedKeys, event) => {
  const { node } = event
  // 只处理用户节点
  if (node.type !== 'user') return

  // 检查节点是否已经被选中
  const isSelected = checkedUserIds.value.includes(node.key)

  if (isSelected) {
    // 如果已经选中，则取消选中
    checkedUserIds.value = checkedUserIds.value.filter((id) => id !== node.key)
    // 从selectedUsers中移除
    selectedUsers.value = selectedUsers.value.filter((user) => user.userid !== node.key)
  } else {
    // 如果未选中，则选中
    if (!checkedUserIds.value.includes(node.key)) {
      checkedUserIds.value.push(node.key)
    }

    // 添加用户到selectedUsers
    const userExists = selectedUsers.value.some((user) => user.userid === node.key)
    if (!userExists) {
      selectedUsers.value.push({
        userid: node.key,
        name: node.title,
        avatar: node.avatar || ''
      })
    }
  }
  // 新增：每次与会人变化都emit最新数据
  emit('get-value', formData.value)
}

const removeReservationUser = () => {
  if (selectedReservationUser.value) {
    // 先保存userid
    const userid = selectedReservationUser.value.userid
    // 移除预约人
    selectedReservationUser.value = null
    treeUser.value = null
    userId = null
    // 同步移除与会人列表
    selectedUsers.value = selectedUsers.value.filter((user) => user.userid !== userid)
    // 选中状态也要清理
    checkedUserIds.value = checkedUserIds.value.filter((id) => id !== userid)
    // 预约人树的选中状态也清理
    selectedReservationKeys.value = [] as string[]
    // 修正：emit前同步treeUser
    formData.value.treeUser = treeUser.value
    emit('get-value', formData.value)
  }
}

const onReservationRadioChange = (key: string) => {
  selectedReservationKeys.value = [key]
  // 修正：emit前同步treeUser
  formData.value.treeUser = treeUser.value
  emit('get-value', formData.value)
}

const onReservationNodeSelect = (selectedKeys, { node }) => {
  if (node.type === 'user') {
    selectedReservationKeys.value = [node.key]
  }
}

function onSubjectInput() {
  emit('get-value', formData.value)
}

// 修改会议室选择逻辑：云会议+现场会议时点击会议室不会自动切换到现场会议
function selectMeetingRoom(id) {
  if (Array.isArray(formData.value.meetRoomId) && formData.value.meetRoomId[0] === id) {
    formData.value.meetRoomId = []
    formData.value.meetType = '1'
  } else {
    formData.value.meetRoomId = [id]
    formData.value.meetType = '0'
  }
}

// 修改watch逻辑：云会议+现场会议时不因选择会议室自动切换meetType
watch(
  [() => formData.value.meetRoomId, () => formData.value.meetType],
  () => {
    emit('get-value', formData.value)
    emit('getMeetingType', formData.value.meetType)
  },
  { deep: true }
)

// 自动回显预约人和与会者
watch(
  () => props.initialUserInfo,
  (val) => {
    if (val && val.userid) {
      // 预约人
      selectedReservationUser.value = {
        userid: val.userid,
        name: val.realname,
        avatar: val.avatar || ''
      }
      treeUser.value = val.userid
      userId = val.userid
      selectedReservationKeys.value = [val.userid]
      // 与会人
      selectedUsers.value = [
        {
          userid: val.userid,
          name: val.realname,
          avatar: val.avatar || ''
        }
      ]
      checkedUserIds.value = [val.userid]
    } else {
      // 清空
      selectedReservationUser.value = null
      treeUser.value = null
      userId = null
      selectedReservationKeys.value = []
      selectedUsers.value = []
      checkedUserIds.value = []
    }
  },
  { immediate: true }
)
// 新增：watch meetingRoomType，确保切tab或弹窗多次打开都能正常渲染
watch(
  () => props.meetingRoomType,
  (val) => {
    if (val === 1) {
      formData.value.meetType = '0'
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.meeting-form {
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #e5e6eb;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: #f7f8fa;
    border-radius: 3px;
  }
}

.meeting-form-content {
  padding: 0 8px;
  width: 100%;
  box-sizing: border-box;
}

.form-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  width: 100%;
    box-sizing: border-box;

  .section-title {
    margin-bottom: 16px;
    font-size: 15px;
    font-weight: 500;
    color: #1d2129;
  }
}

.meeting-type-buttons {
    display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.form-item-full {
  width: 100%;
}

.form-item-half {
  flex: 1;
  min-width: 0;
  max-width: 300px;
  margin-bottom: 0 !important;
}

:deep(.arco-input),
:deep(.arco-picker),
:deep(.arco-input-number) {
  min-height: 32px;
  height: 32px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

:deep(.arco-input-number-inner) {
  height: 100%;
  display: flex;
  align-items: center;
}

:deep(.arco-input-number-input) {
  padding-top: 0;
  padding-bottom: 0;
  line-height: 1.5;
  display: flex;
  align-items: center;
}

:deep(.arco-form-item-label) {
  min-width: 72px;
  display: inline-block;
}

.location-selectors {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  box-sizing: border-box;
}

.location-select {
  width: calc(33.33% - 11px);
  min-width: 120px;
}

.meeting-room-grid {
  margin-top: 20px;
  width: 100%;
  box-sizing: border-box;

  .room-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    width: 100%;
    box-sizing: border-box;
    padding: 8px;
    max-height: 400px;
    overflow-y: auto;
    overflow-x: hidden;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #e5e6eb;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f7f8fa;
      border-radius: 3px;
    }
  }
}

.room-card {
  width: 100%;
  margin-bottom: 16px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  box-sizing: border-box;
  background: #fff;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  .room-content {
    display: flex;
    align-items: flex-start;
    padding: 16px;
    gap: 24px;
    min-height: 180px;
    width: 100%;
    box-sizing: border-box;
  }

  .room-image {
    flex-shrink: 0;
    width: 240px;
    height: 180px;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f7f8fa;

    :deep(img) {
      max-width: 100%;
      max-height: 100%;
      width: auto;
      height: auto;
      object-fit: contain;
      transition: transform 0.3s ease;
      padding: 4px;
    }

    &:hover :deep(img) {
      transform: scale(1.05);
    }
  }

  .room-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    padding: 10px 0;
    width: 100%;
    box-sizing: border-box;

    .room-name {
      font-weight: 500;
      margin-bottom: 16px;
      font-size: 18px;
      color: #1d2129;
      word-break: break-word;
    }

    .room-details {
      display: flex;
      flex-direction: column;
      gap: 12px;
      color: #86909c;
      font-size: 14px;
      width: 100%;
      box-sizing: border-box;

      .detail-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 0;
        border-bottom: none;
        word-break: break-word;

        :deep(.arco-icon) {
          font-size: 16px;
          color: #4e5969;
        }
      }
    }
  }
}

.room-card-selected {
  border: 2px solid #165dff;
  background: #f0f7ff;
}

.cycle-settings {
  padding: 12px;
  background: #f7f8fa;
  border-radius: 4px;
}

.weekday-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.month-days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 6px;

  :deep(.arco-checkbox-group) {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 6px;
  }
  :deep(.arco-checkbox-wrapper) {
    margin: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 2px 0;
    box-sizing: border-box;
    margin-bottom: 8px;
    margin-right: 8px;
  }
  :deep(.arco-checkbox) {
    margin-right: 4px;
  }
}

.warning-text {
  color: #f53f3f;
  font-size: 12px;
  margin-top: 8px;
}

.guest-settings {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attendee-settings {
.selected-users {
  display: flex;
  flex-wrap: wrap;
    gap: 8px;
    margin: 12px 0;
}

.user-card {
  display: flex;
  align-items: center;
    gap: 6px;
    padding: 6px 10px;
    background: #f7f8fa;
    border-radius: 16px;
  position: relative;

.user-avatar {
      width: 20px;
      height: 20px;
  border-radius: 50%;
}

.user-name {
      font-size: 13px;
    }

.delete-btn {
  position: absolute;
      right: -6px;
      top: -6px;
      width: 16px;
      height: 16px;
      line-height: 16px;
      text-align: center;
      background: #f53f3f;
      color: #fff;
  border-radius: 50%;
  cursor: pointer;
      font-size: 10px;
    }
  }
}

.unit-text {
  margin-left: 6px;
  color: #86909c;
  font-size: 13px;
}

.invite-modal-content {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .search-input {
    margin-bottom: 8px;
  }
}

.reservation-user-select {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .search-input {
    margin-bottom: 8px;
  }
}

.selected-user {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f7f8fa;
  border-radius: 4px;

  .user-avatar {
    width: 24px;
    height: 24px;
    border-radius: 50%;
  }

  .user-name {
  font-size: 14px;
    color: #1d2129;
  }
}

.custom-radio input[type='radio'] {
  accent-color: #165dff;
}

/* 预约人选择弹窗树节点样式 */
:deep(.arco-tree-node) {
  width: 100%;
  padding-right: 16px;
}

:deep(.arco-tree-node-title) {
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.arco-tree-node-drag-icon) {
  display: none;
}

:deep(.arco-tree-node-indent + .arco-tree-node-switcher) {
  margin-right: 4px;
}
</style>
